import { Pixijsvue } from '../../main';
import { Scope } from "../../../typings/traverse";
import { Container } from "pixi.js";
import {
    getGoalData,
    absolutePath,
    checkNamespace,
    parseFunctionArgvs,
    parseFunctionName
  } from "../../../utils/index";
import { DepItem } from "../../../typings/dep";
interface DealGoal {
  $data: Record<string, any>;
  $watcher: Record<string, Record<string, Array<Function>>>;
  $style: Record<string, Function>;
  _depList: Array<DepItem>;
  $id: number;
}
export function v_style(
  that: Pixijsvue,
  goal: DealGoal,
  container: Container,
  element: Element,
  scope: Scope | undefined
) {
  // v-style
  if (element.hasAttribute("v-style")) {
    const depName = "style";
    const { $data, $watcher, _depList, $style, $id } = goal;
    // 由于每一个sprite都是被一个container包住的，所以style函数的
    // 第二个参数修改为这个container，如果要对sprite进行更细致的操作
    // 可以直接用container选取children
    let sprite: PIXI.DisplayObject | Container = container;
    let v_style = <string>element.getAttribute("v-style");
    let v_stylePath = parseFunctionName(v_style);

    let _argvs: Array<string> | undefined = parseFunctionArgvs(v_style);
    let argvs: Array<any> = [];
    argvs.push(sprite);

    if (scope) {
      const { items, item } = scope;
      if (_argvs) {
        _argvs = _argvs.map((argv) => {
          let isArgvNamespace = checkNamespace(argv, item);
          if (isArgvNamespace) {
            return absolutePath(items, item, argv);
          } else {
            return argv;
          }
        });
      }
      let isStyleNamespace = checkNamespace(v_stylePath, item);
      if (isStyleNamespace) {
        v_stylePath = absolutePath(items, item, v_stylePath);
      }
    }
    if (_argvs) {
      _argvs.forEach((argv) => {
        argvs.push(getGoalData($data, argv));
      });
    }
    // Object.keys(this.$style).forEach(value => {
    _depList.forEach((item) => {
      item.dep.setDependence(
        v_stylePath,
        depName,
        () => {
          $style[v_stylePath].apply(that, argvs);
        },
        $id
      );
    });
    let fun = () => {
      if (_argvs) {
        argvs = [];
        argvs.push(sprite);
        _argvs.forEach((argv) => {
          argvs.push(getGoalData($data, argv));
        });
      }
      $style[v_stylePath].apply(that, argvs);
    };
    if ($watcher[v_stylePath]) {
      $watcher[depName][v_stylePath] = [];
    }
    $watcher[depName][v_stylePath].push(fun);
  }
}
